<template>
  <div class="gun-1">
    <van-skeleton :row="20" animate />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { getUserInfo } from '@/services/user'
import { useUserStore, useUserStores } from '@/stores'

// 定义常量和引用

const router = useRouter()

const store = useUserStore()
const stores = useUserStores()

// 设置 URL 参数

// 请求用户 ID
const requestUserId = () => {
  const u = navigator.userAgent
  if (u.includes('Android') || u.includes('Linux')) {
    ;(window as any).zafu?.requestInfoFromApp()
  } else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(u)) {
    window.webkit?.messageHandlers?.requestInfoFromApp?.postMessage(null)
  }
}

// 获取追踪编号
const getTrackingNumber = async (authCode: any) => {
  try {
    const res = await getUserInfo({
      authCode
    }) // 这里是接口
    if (res.code == 200) {
      stores.addUsr(res.data.access_token)
      store.apps('co')

      router.replace({ path: '/detailPage' })
    }
  } catch (error) {
    console.error('Failed to get token:', error)
  }
}

// 检查是否为 App 登录
const isAppLogin = (): boolean => {
  const u = navigator.userAgent
  if (u.includes('Android') || u.includes('Linux')) {
    return !!(window as any).zafu?.requestInfoFromApp
  } else if (/\(i[^;]+;( U;)? CPU.+Mac OS X/.test(u)) {
    return !!window.webkit?.messageHandlers?.requestInfoFromApp
  }
  return false
}

// 组件挂载时的操作
onMounted(() => {
  if (isAppLogin()) {
    //alert('检查是否为 App 登录' + isAppLogin())
    ;(window as any).getTrackingNumber = getTrackingNumber
    ;(window as any).infoFromApp = (info: any) => {
      const res = JSON.parse(info)
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const { data } = JSON.parse(xhr.responseText)
          console.log('获取到的authcode:', data)
          getTrackingNumber(data)
        }
      }
      const urlAuth = 'https://app.zafu.edu.cn/app/app/authcode.jhtm'
      xhr.open(
        'POST',
        `${urlAuth}?userId=${res.userId}&t=${Math.random()}`,
        true
      )
      xhr.send()
    }
    requestUserId()
  } else {
    alert('走原来的')
    store.casLogins() //重新登录
    store.apps('so')
  }
})
</script>

<style lang="scss" scoped>
.gun-1 {
  padding-top: 20px;
}
</style>
